package io

type Publisher interface {
	Publish(topic string, p []byte) error
}

type MessageReadWriteCloser interface {
	MessageReader
	WriteCloser
}

type MessageReadCloser interface {
	MessageReader
	Closer
}

type MessageReader interface {
	// ReadMessage 读取拆包后的数据
	ReadMessage() ([]byte, error)
}

func PublisherToWriter(p Publisher, topic string) Writer {
	return &publishToWriter{topic: topic, Publisher: p}
}

type publishToWriter struct {
	topic string
	Publisher
}

func (this *publishToWriter) Write(p []byte) (int, error) {
	err := this.Publisher.Publish(this.topic, p)
	return len(p), err
}

//type ReadFunc func(r Reader) (bytes []byte, err error)
//
//type MessageReadCloser interface {
//	MessageReader
//	Closer
//}
//
//type MessageReader interface {
//	// ReadMessage 读取拆包后的数据
//	ReadMessage() ([]byte, error)
//}
//
//type messageReader struct {
//	buf      *bufio.Reader
//	readFunc ReadFunc
//}
//
//// SetReadFunc 设置读取函数,默认读取全部
//func (this *messageReader) SetReadFunc(fn ReadFunc) *messageReader {
//	this.readFunc = fn
//	return this
//}

//// ReadMessage 读取数据 实现接口 MessageReader
//func (this *messageReader) ReadMessage() ([]byte, error) {
//	if this.readFunc == nil {
//		this.readFunc = ReadWithAll
//	}
//	return this.readFunc(this.buf)
//}
//
//func NewMessageReader(reader io.Reader) *messageReader {
//	m := &messageReader{buf: bufio.NewReader(reader)}
//	m.SetReadFunc(ReadWithAll)
//	return m
//}
